<template>
    <el-select
      ref="remoteSearch"
      v-model="comValue"
      :multiple="multiple"
      collapse-tags-tooltip
      style="width: 240px"
      :disabled="disabled"
      filterable
      remote
      clearable
      remote-show-suffix
      reserve-keyword
      :remote-method="remoteMethod"
      @input.enter="input"
      @clear="clearInput"
      @blur="blurSelect"
      placeholder="请选择"
    >
      <el-checkbox
        v-if="props.hasSelectAll"
        style="margin-left: 20px"
        v-model="isSelectAll"
        @change="selectAll"
      >
        全选
      </el-checkbox>
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
      <div v-show="loading" class="loading" v-loading="loading"></div>
      <div
        v-if="!loading && currentPageData.length > 0"
        ref="moreDiv"
        class="search-keyword"
      >
        <span @click="loadMore">加载更多...</span>
      </div>
      <div v-if="currentPageData.length == 0" class="search-keyword-bottom">
        <span>到底啦~</span>
      </div>
    </el-select>
  </template>
  
  <script setup>
  import { debounce } from '@/utils/debounce.js'
//   import {
//     service_quality_tasks_getOrg,
//     service_quality_tasks_getOrg2
//   } from '@/api/FWJGGL/FWZLJC/index.js'
  import { prop } from 'dom7'
  import { ref, computed, onBeforeMount, reactive } from 'vue'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import {
    Delete,
    Edit,
    Search,
    Share,
    Upload,
    Plus,
    Warning
  } from '@element-plus/icons-vue'
  
  const props = defineProps({
    areaCode:{
      type:String,
      default:''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    hasSelectAll: {
      type: Boolean,
      default: false
    },
    orgType: {
      type: [Number, String],
      default: 2
    },
    needSub: {
      type: Boolean,
      default: false
    },
    areaStr: {
      type: String
    },
    name: {
      type: String
    },
    modelValue: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  })
  
  const emit = defineEmits([
    'update:modelValue',
    'update:name',
    'update:areaStr',
    'change',
    'typeChange'
  ])
  const options = ref([])
  
  const loading = ref(false)
  const remoteSearch = ref(null)
  const currentPageData = ref([])
  const state = reactive({
    search: {
      pageNum: 1,
      pageSize: 20
    }
  })
  
  const loadMore = () => {
    state.search.pageNum += 1
    getOrgList()
  }
  
  const clearInput = () => {
    options.value = []
    state.search.pageNum = 1
    state.search.orgName = ''
    getOrgList()
  }
  
  const input = debounce(
    value => {
      console.log('输入查询')
      options.value = []
      state.search.pageNum = 1
      state.search.orgName = value.target.value
      loading.value = true
      if (props.orgType) {
        state.search.orgType = props.orgType
        state.search.needSub = props.needSub
        state.search.areaCode = props.areaCode
  
        service_quality_tasks_getOrg(state.search).then(res => {
          options.value = res.data
          currentPageData.value = res.data
          loading.value = false
        }) // orgType：2养老机构 3社区机构 // needSub:false当前行政级别的直属机构 true获取当前行政级别直属机构及下属单位的机构
      } else {
        state.search.orgType = 2
        state.search.needSub = true
        state.search.areaCode = props.areaCode
        service_quality_tasks_getOrg(state.search).then(res => {
          options.value = res.data
          currentPageData.value = res.data
          loading.value = false
        }) // 获取当前行政级别直属机构及下属单位的养老机构
      }
    },
    1000,
    false
  )
  
  const remoteMethod = query => {
    // console.log('查询')
    // if (query !== '') {
    //   getOrgList()
    // } else {
    //   options.value = []
    // }
  }
  
  const isSelectAll = ref(false)
  const selectAll = flag => {
    if (flag) {
      let arr = []
      options.value.map(item => {
        arr.push(item.id)
      })
      emit('update:modelValue', arr.join())
    } else {
      emit('update:modelValue', '')
    }
  }
  
  // 这里有个bug目前未解决 lazy组件中如果复制文字进行检索 会出现数据源问题
  const blurSelect = () => {
    if (options.value.length == 0) {
      console.log('清空2');
      options.value = []
      state.search.pageNum = 1
      state.search.orgName = ''
      getOrgList()
    }
  }
  
  const comValue = computed({
    get() {
      console.log(comValue)
      if (props.multiple) {
        if (props.modelValue) {
          let count = props.modelValue.split(',').length
          if (count == options.value.length) {
            isSelectAll.value = true
          } else {
            isSelectAll.value = false
          }
        }
        return props.modelValue ? props.modelValue.split(',') : []
      }
      return props.modelValue
    },
    set(val) {
      console.log(comValue)
  
      if (props.multiple) {
        emit('update:modelValue', val.join())
      } else {
        emit('update:modelValue', val)
        if (val) {
          let target = options.value.filter(item => item.id == val)[0]
          emit('typeChange', target.type)
          emit('update:name', target.name)
          emit('update:areaStr', target.areaCode)
          emit('change', target)
        }
      }
    }
  })
  
  const getOrgList = async () => {
    // let res
    // loading.value = true
    // if (props.orgType) {
    //   state.search.orgType = props.orgType
    //   state.search.needSub = props.needSub
    //   state.search.areaCode = props.areaCode
    //   res = await service_quality_tasks_getOrg(state.search) // orgType：2养老机构 3社区机构 // needSub:false当前行政级别的直属机构 true获取当前行政级别直属机构及下属单位的机构
    // } else {
    //   state.search.orgType = 2
    //   state.search.needSub = true
    //   state.search.areaCode = props.areaCode
    //   res = await service_quality_tasks_getOrg(state.search) // 获取当前行政级别直属机构及下属单位的养老机构
    // }
    // currentPageData.value = res.data
    // options.value.push(...res.data)
    // loading.value = false
  }
  
  onBeforeMount(async () => {
    getOrgList()
  })
  </script>
  
  <style lang="scss">
  .loading {
    margin: 0 auto;
    width: 20px;
    height: 20px;
  }
  .search-keyword {
    span {
      display: block;
      width: 100%;
      height: 30px;
      line-height: 30px;
      text-align: center;
      // padding-left: 20px;
      cursor: pointer;
      color: #087cd6;
    }
  }
  .search-keyword-bottom {
    width: 100%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    // padding-left: 20px;
    color: #606266;
  }
  </style>
  